package com.code2roc.fastboot.system.common.bizlogic;

import com.code2roc.fastboot.system.common.model.SystemJobDO;
import com.code2roc.fastboot.system.common.service.ISystemJobService;
import com.code2roc.fastboot.system.enums.JobEnum;
import com.code2roc.fastboot.model.BaseBootLogic;
import com.code2roc.fastboot.framework.quartz.QuartzUtil;
import org.quartz.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JobLogic extends BaseBootLogic {
    private static Logger log = LoggerFactory.getLogger(JobLogic.class);
    @Autowired
    private ISystemJobService service;
    @Autowired
    private QuartzUtil quartzUtil;

    @Async
    public void initQuartzTask() {
        List<SystemJobDO> jobDOList = service.selectAllList();
        for (SystemJobDO entity : jobDOList) {
            if (entity.getJob_status() == JobEnum.JobStatus.Open.get_value()) {
                startTask(entity);
            }
        }
        if (jobDOList.size() > 0) {
            log.debug("扫描并初始化开启quartz定时任务成功，任务数量：" + jobDOList.size() + "个");
        }
    }

    public void updateStatus(String row_id, int job_status) {
        SystemJobDO entity = service.selectOne(row_id);
        quartzUtil.deleteJob(entity.getJob_name());
        if (job_status == JobEnum.JobStatus.Open.get_value()) {
            startTask(entity);
        }
        entity.setJob_status(job_status);
        service.update(entity);
    }

    public void executeOnce(String row_id) throws Exception {
        SystemJobDO entity = service.selectOne(row_id);
        Class<Job> jobClass = (Class<Job>) Class.forName(entity.getJob_class_path());
        quartzUtil.executeOnce(entity.getJob_name(),jobClass);
    }

    private void startTask(SystemJobDO entity) {
        try {
            Class<Job> jobClass = (Class<Job>) Class.forName(entity.getJob_class_path());
            if (entity.getJob_type() == JobEnum.JobType.CycleJob.get_value()) {
                quartzUtil.addIntervalJob(entity.getJob_name(), jobClass, entity.getExecute_peroid(), entity.getExecute_unit());
            } else {
                quartzUtil.addCornJob(entity.getJob_name(), jobClass, entity.getCorn_express());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
